/*
 * @Author: jingzi 1163478123@qq.com
 * @Date: 2025-04-29 20:25:42
 * @LastEditors: jingzi 1163478123@qq.com
 * @LastEditTime: 2025-11-08 16:44:47
 * @Description: gitlab 代码仓库处理
 * Copyright (c) 2025 by ${git_name}, All Rights Reserved.
 */
import { gitlabToJenkins } from '../config/index.js'
import { postFormData } from '../utils/http'
import { getStorageData, setStorageData, copyToClipboard } from '../utils'
import '../styles/index.less'
(function () {
  const href = location.href // 获取当前页面地址
  // 判断是否是gitlab页面
  if (!href.includes('192.168.5.143')) {
    return
  }

  const projectName = document.querySelector('.sidebar-context-title').textContent.replaceAll('\n','') // 获取项目名称
  // 跳转tag列表，触发侧边栏的标签点击事件
  const goTagPage = () =>{
    const sideBar = document.querySelector('.sidebar-top-level-items')
    const tag = sideBar.childNodes[2].querySelector('.sidebar-sub-level-items').childNodes[7].querySelector('a')
    console.log(tag,'====')
    tag.click()
  }
  const tagPageHandle = () =>{
    const title = document.querySelector('.nav-text')
    const CICD_BTN = `<button class="tag-btn" id="cicdBox">到CICD</button>`
    const RELOAD_BTN = `<button class="tag-btn" id="reloadBtn">刷新页面</button>`

    if(title){
      // title.insertAdjacentHTML('afterend',CICD_BTN)
      title.insertAdjacentHTML('afterend',RELOAD_BTN)
    }
    const cicdBox = document.querySelector('#cicdBox')
    const reloadBox = document.querySelector('#reloadBtn')
    cicdBox?.addEventListener('click',()=>{
      const sideBar = document.querySelector('.sidebar-top-level-items')
      const tag = sideBar.childNodes[5].querySelector('.qa-link-pipelines')
      tag.click()
    })
    reloadBox?.addEventListener('click',()=>{
      window.location.reload()
    })
  }
  // 添加跳转tag列表按钮
  const addTagBtn = () =>{
    const title = document.querySelector('.project-title-row')
    const diffDom = document.querySelector('.detail-page-description')
    const navControls = document.querySelector('.nav-controls')
    const TAGBTN = `<button class="tag-btn" id="tagBox">跳转tag列表</button>`
    if(diffDom){
      // 合并页面
      diffDom.insertAdjacentHTML('afterend',TAGBTN)
    }else if(title){
      // 项目首页
      title.insertAdjacentHTML('afterend',TAGBTN)
    } else if (navControls) {
      const firstBtn = navControls.querySelector('.js-run-pipeline')
      if(firstBtn){
        firstBtn.style.marginLeft = '10px'
      }
      // 在nav-controls前面插入按钮
      navControls.insertAdjacentHTML('afterbegin', TAGBTN)
    }

    const tagBox = document.querySelector('#tagBox')
    tagBox?.addEventListener('click',goTagPage)
  }
  // 自动打Tag执行
  const autoTagFun = async () =>{
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
    const gitMergeContainer = document.querySelector('.git-merge-container')
    const branchName = gitMergeContainer.querySelectorAll('.label-branch')[1].textContent
    const description = document.querySelector('.detail-page-description')
    const tagMessage = description.querySelector('h2').textContent.trim()
    const url = `${href.split(projectName)[0]}${projectName}/tags`
    const date = new Date()
    const tagName = `v${date.getFullYear()}.${date.getMonth()}.${date.getDate()}_${branchName.trim()}_${date.getHours()}${date.getMinutes()}${date.getSeconds()}`
    const formData = new FormData()
    formData.append('utf8', decodeURIComponent('%E2%9C%93'))
    formData.append('tag_name', tagName)
    formData.append('authenticity_token', csrfToken)
    formData.append('ref', branchName)
    formData.append('message', tagMessage)
    formData.append('release_description', '')
    postFormData(url, formData)
  }
  // 自动添加tag列表按钮并跳转到发版
  const autoAddTagAndGoJenkinsBtn = () =>{
    const title = document.querySelector('.project-title-row')
    const diffDom = document.querySelector('.detail-page-description')
    const navControls = document.querySelector('.nav-controls')
    const TAGBTN = `<button class="tag-btn" id="autoAddTagAndGoJenkins">自动打Tag并去发布</button>`
    if(diffDom){
      // 合并页面
      diffDom.insertAdjacentHTML('afterend',TAGBTN)
    }else if(title){
      // 项目首页
      title.insertAdjacentHTML('afterend',TAGBTN)
    } else if (navControls) {
      const firstBtn = navControls.querySelector('.js-run-pipeline')
      if(firstBtn){
        firstBtn.style.marginLeft = '10px'
      }
      // 在nav-controls前面插入按钮
      navControls.insertAdjacentHTML('afterbegin', TAGBTN)
    }

    const tagBox = document.querySelector('#autoAddTagAndGoJenkins')
    tagBox?.addEventListener('click',autoTagFun)
  }
  const goToJenkins = async (event) =>{
    // 阻止事件冒泡
    event.stopPropagation()
    const parentDom = event.target.parentElement
    parentDom.style.border = "2px solid red";
    parentDom.style.backgroundColor = "rgba(255, 0, 0, 0.1)";
    const tag = event.target.dataset.tag // 找到tag
    const time = event.target.dataset.time;
    const elementData = {
      projectName,
      tag,
      time,
    };
    const selectedElements = await getStorageData('selectedElementData') || []
    const findIndex = selectedElements.findIndex(item=>item.tag === tag && item.projectName === projectName)
    if(findIndex === -1){
      selectedElements.unshift(elementData)
    }else{
      selectedElements[findIndex] = elementData
    }
    if(selectedElements.length > 20){
      selectedElements.pop()
    }
    await setStorageData('selectedElementData', selectedElements)
    window.open(`${gitlabToJenkins[projectName]}build?delay=0sec`,'_blank')
  }
  const addToJenkinsBtn = () => {
    const maxCount = 5; // 最大添加数量
    const listBox = document.querySelector('.content-list')
    const items = listBox?.querySelectorAll('li.flex-row')
    items.forEach((item,index)=>{
      if(index < maxCount){
        const tag = item.querySelector('.ref-name').textContent // 找到tag
        const addBox = item.querySelector('.ref-name')
        const time = item.querySelector(".js-timeago-render").textContent;
        const btn = `<button data-tag="${tag}" data-time="${time}" style="margin-left: 10px;" class="go-btn">去发版</button>`
        addBox.insertAdjacentHTML('afterend',btn)
      }
    })
    const btnDom = document.querySelectorAll('.go-btn')
    btnDom.forEach(btn=>{
      btn.addEventListener('click',(event)=>{
        goToJenkins(event)
      })
    })
  }
  // 增加监听信息
  const messageHandle = () => {
    // 监听来自sidepanel及其popup的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      console.log("Received message:", request);

      if (request.action === "selectAll") {
        
      }
      return true; // 保持消息通道开放
    });
  }
  // 在commit页面增加按钮
  const addCommitBtn = () => {
    const commitBtn = document.querySelector('#commits-list')
    commitBtn.querySelectorAll('.commits-row .commit').forEach(item=>{
      const commitMessage = item.querySelector('.commit-row-message')?.textContent
      if(commitMessage?.includes('Merge branch')){
        const commitBox = item.querySelector('.commit-actions')
        commitBox.insertAdjacentHTML('afterbegin', `<button class="tag-btn copybtn">复制信息</button>`)
      }
    })
    const copyBtn = document.querySelectorAll('.copybtn')
    copyBtn.forEach(btn=>{
      btn.addEventListener('click',(event)=>{
        const commitBox = event.target.parentElement
        const commitInfo = commitBox.querySelector('.commit-sha-group button').dataset.clipboardText
        copyToClipboard(`codereview下这个${commitInfo}的change是否异常`)
      })
    })
  }
  // 页面加载的方法
  const handlePageLoad = () => {
    const { href } = location
    // 标签页面增加按钮
    if(href.includes('tags')){
      addToJenkinsBtn()
    }
    // 自动打Tag执行
    // if(href.includes('merge_requests')){
    //   autoAddTagAndGoJenkinsBtn()
    // }
    messageHandle()
    if(href.includes('tags')){
      tagPageHandle()
    }
    if(href.includes('/commits')){
      addCommitBtn()
    }
    const timer = setTimeout(()=>{
      addTagBtn()
    },300)
    return () => clearTimeout(timer)
  };
  // 在页面加载完成时执行
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', handlePageLoad);
  } else {
    handlePageLoad();
  }
})();
